package com.iot.framework.mobile.token;

import com.iot.common.core.domain.entity.SysUser;
import com.iot.common.core.domain.model.LoginUser;
import com.iot.common.utils.CharUtils;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 维护用户token
 */
public class UserTokenManager {
    private static Map<String, UserToken> tokenMap = new HashMap<>();
//    private static Map<Long, UserToken> idMap = new HashMap<>();
//    private static Map<Long, UserTable> userMap = new HashMap<>();

    public static UserToken getToken(String token) {
        return tokenMap.get(token);
    }

    public static Long getUserId(String token) {
        SysUser sysUser = getUser(token);
        if (sysUser == null) {
            return null;
        }
        return sysUser.getUserId();
    }

    public static SysUser getUser(String token) {
        UserToken userToken = tokenMap.get(token);
        if (userToken == null) {
            return null;
        }

        if (userToken.getExpireTime().isBefore(LocalDateTime.now())) {
            tokenMap.remove(token);
//            idMap.remove(userToken.getUserId());
            return null;
        }

        return userToken.getSysUser();
    }

//    public static UserTable getUserById(Integer id){
//        return idMap.get(id).getUserTable();
//    }

    public static UserToken generateToken(SysUser user) {
        return generateToken(user, false, false);
    }

    public static UserToken generateToken(SysUser user, boolean isCustomer, boolean isInstaller) {
        UserToken userToken = new UserToken();
        String token = CharUtils.getRandomString(32);
        while (tokenMap.containsKey(token)) {
            token = CharUtils.getRandomString(32);
        }
        LocalDateTime update = LocalDateTime.now();
        LocalDateTime expire = update.plusDays(1);

        userToken.setToken(token);
        userToken.setUpdateTime(update);
        userToken.setExpireTime(expire);
        userToken.setUserId(user.getUserId());
        userToken.setSysUser(user);
        userToken.setCustomer(isCustomer);
        userToken.setInstaller(isInstaller);
        tokenMap.put(token, userToken);

        return userToken;
    }

    public static void removeToken(UserToken userToken) {
        String token = userToken.getToken();
        tokenMap.remove(token);
    }

    public static void clear() {
        Collection<UserToken> userTokenCollection = tokenMap.values();
        for(UserToken userToken : userTokenCollection){
            if(userToken.getExpireTime().isBefore(LocalDateTime.now())){
                tokenMap.remove(userToken.getToken());
//                idMap.remove(userToken.getUserId());
            }
        }
    }

    public static void setToken(LoginUser loginUser) {

    }
}
